﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ur3
{
    class Pipe
    {
        public static void StartClient()
        {
            ProcessStartInfo info = new ProcessStartInfo();
            //info.FileName = "C:\\Users\\jhanbin\\Documents\\Visual Studio 2015\\Projects\\cutter\\Debug\\camera.exe";
            info.FileName = "C:\\Users\\jhanbin\\Documents\\Visual Studio 2015\\Projects\\cutter\\x64\\Debug\\camera.exe";
            info.Arguments = "";
            //info.WindowStyle = ProcessWindowStyle.Minimized;
            Process pro = Process.Start(info);
            //pro.WaitForExit();  
        }

        public static string ServerRead(string pipename = "testpipe")
        {
            // 创建命名管道
            NamedPipeServerStream pipeServer = new NamedPipeServerStream(pipename);

            StartClient();

            //  等待客户端连接
            pipeServer.WaitForConnection();
            Console.WriteLine("Client connected.");
            StreamReader sr = new StreamReader(pipeServer);
            string s1 = sr.ReadLine();
            Console.WriteLine("ServerRead: " + s1);
            pipeServer.Close();
            return s1;
        }


        public static void ServerWrite(string str, string pipename = "testpipe")
        {
            // 创建命名管道
            NamedPipeServerStream pipeServer = new NamedPipeServerStream(pipename);

            StartClient();

            //  等待客户端连接
            pipeServer.WaitForConnection();
            Console.WriteLine("Client connected.");
            StreamWriter sw = new StreamWriter(pipeServer);
            sw.AutoFlush = true;
            sw.WriteLine(str);
            Console.WriteLine("ServerWrite: " + str);
            pipeServer.Close();
        }


        public static string ClientRead(string pipename = "testpipe")
        {
            NamedPipeClientStream pipeClient = new NamedPipeClientStream(pipename);
            pipeClient.Connect();
            Console.WriteLine("Server connected.");
            StreamReader sr = new StreamReader(pipeClient);
            string s1 = sr.ReadLine();
            Console.WriteLine("ClientRead: " + s1);
            pipeClient.Close();
            return s1;
        }

        public static void ClientWrite(string str, string pipename = "testpipe")
        {
            NamedPipeClientStream pipeClient = new NamedPipeClientStream(pipename);
            pipeClient.Connect();
            Console.WriteLine("Server connected.");
            StreamWriter sw = new StreamWriter(pipeClient);
            sw.AutoFlush = true;
            sw.WriteLine(str);
            Console.WriteLine("ClientWrite: " + str);
            pipeClient.Close();
        }

    }
}
